package com.dengcj.epl.service.util;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dengcj.epl.cache.TokenCache;
import com.dengcj.epl.entity.ApiResponseResult;
import com.dengcj.epl.entity.ecology.Ecology;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dengchunjie
 * @Description: Ecology接口工具类
 * @date 2022/1/15 12:27
 */
public class EcologyApiUtil {

    private void regist() {
        //获取当前系统RSA加密的公钥
        RSA rsa = new RSA();
        String publicKey = rsa.getPublicKeyBase64();
        String privateKey = rsa.getPrivateKeyBase64();
        // 调用ECOLOGY系统接口进行注册
        String data = HttpRequest.post(Ecology.getHost() + "/api/ec/dev/auth/regist")
                .header("appid",Ecology.getApiAppid())
                .header("cpk",publicKey)
                .timeout(3000)
                .execute().body();

        System.out.println(data);
    }

    public static String getToken() {
        // 先从缓存中读取
        String token = TokenCache.getEcologyApiToken();
        if(StrUtil.isNotBlank(token)){
            System.out.println("从缓存中读取Token:"+token);
            return token;
        }

        if(StrUtil.isBlank(Ecology.getApiSpk()) || StrUtil.isBlank(Ecology.getApiSecret())){
            System.out.println("spk:"+Ecology.getApiSpk()+",secret:"+Ecology.getApiSecret());
            return "";
        }

        // 公钥加密,所以RSA对象私钥为null
        RSA rsa = new RSA(null,Ecology.getApiSpk());
        //对秘钥进行加密传输，防止篡改数据
        String encryptSecret = rsa.encryptBase64(Ecology.getApiSecret(), CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey);

        System.out.println("encryptSecret:"+encryptSecret);

        //调用ECOLOGY系统接口进行注册
        String data = HttpRequest.post(Ecology.getHost()+ "/api/ec/dev/auth/applytoken")
                .header("appid",Ecology.getApiAppid())
                .header("secret",encryptSecret)
                .header("time","3600")
                .execute().body();

        System.out.println(data);

        Map<String,Object> datas = JSONUtil.parseObj(data);
        token = StrUtil.nullToEmpty((String)datas.get("token"));

        System.out.println("从接口重新获取Token:"+token);

        // 写入缓存
        TokenCache.setEcologyApiToken(token, 3550000L);
        return token;
    }

    /**
     * 通用的请求Ecoloyg接口方法
     * @param operUser 用户ID
     * @param url 接口地址
     * @param params 接口参数
     * @return
     */
    public static ApiResponseResult commonRequest(int operUser, String url, Map<String, Object> params){
        String result ="";

        ApiResponseResult apiResponseResult = new ApiResponseResult();
        Map<String, String> heads = new HashMap<>();
        String token = getToken();
        if(StrUtil.isBlank(token)){
            System.out.println("获取Ecology API token失败");
            apiResponseResult.setFailed("获取Ecology API token失败");
            return apiResponseResult;
        }
        heads.put("token", token);
        heads.put("appid", Ecology.getApiAppid());
        RSA rsa = new RSA(null, Ecology.getApiSpk());
        String secretUserid = rsa.encryptBase64(String.valueOf(operUser), CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey);
        System.out.println(secretUserid);
        heads.put("userid", secretUserid);

        System.out.println("调用Ecology API requestParam:"+params.toString());
        try {
            System.out.println("调用Ecology API URL:"+Ecology.getHost() + url);
            result = HttpRequest.post(Ecology.getHost() + url)
                    .headerMap(heads, true)
                    //.body(requestBody)
                    .form(params)
                    .execute().body();

            System.out.println("调用Ecology API responseBody:"+result);

            if(JSONUtil.isJson(result)){
                JSONObject resultJson = new JSONObject(result);
                if("SUCCESS".equals(resultJson.getStr("code"))){
                    apiResponseResult.setSuccess(resultJson.getJSONObject("data"));
                } else {
                    apiResponseResult.setFailed(resultJson.getStr("errMsg"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            apiResponseResult.setFailed(e.getMessage());
        }

        return apiResponseResult;
    }

    public static void main(String[] args) {
        Ecology.init();
        EcologyApiUtil ecologyApiUtil = new EcologyApiUtil();
        ecologyApiUtil.regist();
    }
}
